<template>
    <div class="ui-select">
        <p class="ui-select-value" @click="checkInput()">{{modelValue}}<span class="small" v-if="!modelValue">{{placeholder||'请选择'}}</span></p>
        <div class="select-option" v-if="dp">
            <p v-for="item in option" :key="item.value" @click="getVal(item)">{{item.label}}</p>
        </div>
    </div>
</template>
<script setup>
import {defineProps, defineEmits, ref, onBeforeUnmount} from 'vue'
const props = defineProps(['option', 'modelValue', 'placeholder'])
const emit = defineEmits(['update:modelValue','getItem'])
let dp = ref(false)
// 将选中的值和对象抛出去
function getVal (item) {
    emit('update:modelValue', item.label);
    emit('getItem', item);
}
// 隐藏下拉
const cancelFun = () => dp.value = false
onBeforeUnmount(() => window.removeEventListener('click', cancelFun))
window.addEventListener('click', cancelFun, true)
// 点击选择框
const checkInput = () => {
    if(props.option.length) {
        dp.value = !dp.value
    }
}
</script>
<style scoped>
.ui-select{
    position: relative;
    height: 34px;
    line-height: 34px;
    padding: 0 6px;
    border: 1px solid #b7babc;
    display: inline-block;
    border-radius: 4px;
    min-width: 140px;
    margin: 4px;
}
.ui-select-value{
    height: 34px;
    line-height: 34px;
    cursor: pointer;
    margin: 0;
}
.select-option{
    position: absolute;
    top: 34px;
    max-height: 40vh;
    width: 100%;
    overflow-y: auto;
    border: 1px solid #b7babc;
    left: 0;
    border-radius: 4px;
    z-index: 999;
    background: #fff;
}
.select-option p{
    white-space: nowrap;
    padding: 0 10px;
    cursor: pointer;
    transition: .3s;
}
.select-option p:hover{
    background: rgb(232, 234, 238);
}
.ui-select-value .small{
    color: #a5a8aa;
}
</style>